import { IAsyncState } from './IAsyncState';

/**
 * 跟踪 promise 的执行过程，状态，时间点，成功失败结果
 * 灵感来自 vue 项目的 spost 规格
 */
export function asTrackPromise(as: IAsyncState, promise: Promise<any>) {
  // 开始执行
  as.ss(ts => {
    const newAs: IAsyncState = {...ts,
      s: ts.s + 1,
      o: false,
      e: false,
      p: true,
      b: new Date(),
      f: undefined,
      r: null,
      d: undefined,
      };
    // 此处可以插入中间件，或者是 hook 来影响处理过程
    return newAs;
  });
  return new Promise((resolve, reject) => {
    promise
      .then(result => {
        as.ss(ts => {
          const newAs: IAsyncState = {
            ...ts,
            p: false,
            o: true,
            d: result,
            rsp: result,
            f: new Date(),
          }
          return newAs;
        });
        resolve(as);
      }).catch(e => {
        as.ss(ts => {
          const newAs: IAsyncState = {
            ...ts,
            p: false,
            e: true,
            E: e,
            f: new Date(),
          }
          return newAs;
        });
        reject(as);
      });
  });
}
